import {
  AfterContentInit, AfterViewInit, Component, ElementRef, OnDestroy, OnInit, Renderer2, ViewChild,
  ViewEncapsulation
} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {SaleService} from "../sale.service";
import {Subject} from "rxjs/Rx";

import {ToolsService} from "@shared/service/tools/tools.service";
import {AuthService} from "@shared/service/auth/auth.service";
import {TrainSaleStudentRespVO} from "@interface/index";



export class TabStatus {
  hasFinish = false;
  showScrollMsg = false;
}

@Component({
  selector: 'seed-sale-detail',
  templateUrl: './sale-detail.component.html',
  styleUrls: ['./sale-detail.component.scss'],
  encapsulation: ViewEncapsulation.None,
})

export class SaleDetailComponent implements OnInit, OnDestroy {
  public dataStore = {
    follow: {
      page: 1,
      list: [],
      hasLoad: false,
    },
    trial: {
      page: 1,
      list: [],
      hasLoad: false,
    },
    studentInfo: new TrainSaleStudentRespVO()
  };
  // 初始化方法待改进
  public tabStatusArr: TabStatus[] = [new TabStatus(), new TabStatus(), new TabStatus()];
  public currentIndex = 0;
  public studentId = '';  // 学员Id
  public orgId = '';  // 组织Id
  public saleUserId = '';  // 销售员Id
  // public studentInfo: TrainSaleStudentRespVO = new TrainSaleStudentRespVO();
  // public studentInfo$: Observable<TrainSaleStudentRespVO>;
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  @ViewChild('record') modalRecord;
  @ViewChild('master') master;
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public isShowDropDown = false;
  public statusArr = ['初始状态', '试课阶段', '试课结束', '跟进中', '流失学员', '正式学员'];  // 对应接口返回的值
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private saleService: SaleService,
    private ele: ElementRef,
    private render: Renderer2,
    private tools: ToolsService,
    private authService: AuthService
  ) {
    this.route.params.subscribe(param => {
      this.studentId = param['studentId'];
      this.orgId = this.authService.getAuthOrgId();
      this.saleUserId = param['saleUserId'];
    });
  }

  /**
   * tab 选择
   * @param tabInfo
   */
  selectIndex(tabInfo) {
    this.currentIndex = tabInfo.index;
    if (this.infiniteScroll && !this.tabStatusArr[tabInfo.index].hasFinish) {
      this.infiniteScroll.enable(true);
    } else {
      this.infiniteScroll.enable(false);
    }
  }

  /**
   * 请求数据
   * @param {number} index 0：跟进记录，1: 试课
   */
  getInfo(index: number) {
    // console.log(index);
    if (index === 0) {
      this.getFollowInfo();
    } else if (index === 1) {
      this.getClassInfo();
    }
  }

  /**
   * 请求 跟进记录
   */
  getFollowInfo() {
    this.saleService.getSalesFollowInfo(this.orgId, this.studentId, this.dataStore.follow.page)
      .subscribe(res => {
        if (res.result === '0') {
          this.dataStore.follow.list = [...this.dataStore.follow.list, ...res.data.list];
          const tabStatusArr = this.tabStatusArr[0];
          if (!tabStatusArr.showScrollMsg && this.dataStore.follow.list.length > 9) {
            tabStatusArr.showScrollMsg = true;
          }
          this.dataStore.follow.page++;
          if (!res.data.hasNextPage) {
            this.infiniteScroll.enable(false);
            tabStatusArr.hasFinish = true;
          }
        } else {
          this.tools.showToast(res.msg);
        }
        this.dataStore.follow.hasLoad = true;
      });
  }

  /**
   * 请求 学员信息
   */
  getSalesCustomInfo() {
    this.saleService.getSalesCustomInfo(this.orgId, this.studentId)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        if (res.result === '0' && res.data) {
          this.dataStore.studentInfo = res.data;
        } else {
          this.tools.showToast(res.msg);
        }
      });
  }

  /**
   * 请求 学员试课信息
   */

  getClassInfo() {
    this.saleService.getSalesTestList(this.orgId, this.studentId, this.dataStore.trial.page)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        if (res.result === '0') {
          this.dataStore.trial.page++;
          this.dataStore.trial.list = [...this.dataStore.trial.list, ...res.data.list];
          const tabStatusArr = this.tabStatusArr[1];
          if (!tabStatusArr.showScrollMsg && this.dataStore.trial.list.length > 9) {
            tabStatusArr.showScrollMsg = true;
          }
          if (!res.data.hasNextPage) {
            this.infiniteScroll.enable(false);
            tabStatusArr.hasFinish = true;
          }
        } else {
          this.tools.showToast(res.msg);
        }
        this.dataStore.trial.hasLoad = true;
      });
  }

  showEditRecord() {
    this.modalRecord.show();
  }

  /**
   * 保存编辑的跟进记录
   * @param {string} val
   */
  saveRecord(val: string) {
    // console.log(val);
    const cont = {
      content: val,
      orgUserId: this.orgId,
      studentId: this.studentId
    };
    this.tools.showLoading();
    this.saleService.addFollowRecord(cont)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        this.tools.hideLoading();
        if (res.result === '0') {
          this.modalRecord.hide();
          this.modalRecord.goBack();
          this.dataStore.follow.page = 1;
          this.tabStatusArr[0].hasFinish = false;
          if (this.currentIndex === 0) {
            this.infiniteScroll.enable(true);
          }
          this.tabStatusArr[0].showScrollMsg = false;
          this.dataStore.follow.list = [];
          this.getFollowInfo();
        } else {
          this.tools.showToast(res.msg);
        }
      });
  }

  /**
   * 转跳到办理报名去
   */
  goToRegistration() {
    this.router.navigate([`/sale/apply-registration/${this.studentId}/${this.saleUserId}`]);
  }

  /**
   * 转跳到添加试课的列表
   */
  goToClassList() {
    const that = this;
    this.router.navigate([`/sale/course/${this.studentId}/${this.saleUserId}`]);
  }

  /**
   *  打开假的 dropDown 模块
   */
  showDropDown() {
    this.isShowDropDown = true;
    setTimeout(() => {
      const drop = this.ele.nativeElement.querySelector('.drop-down');
      const dropEleTop = this.master.nativeElement.getBoundingClientRect().bottom;
      this.render.setStyle(drop, 'top', dropEleTop + 'px');
    }, 0);
  }

  /**
   *  关闭假的 dropDown 模块
   */
  hideDropDown() {
    this.isShowDropDown = false;
  }

  setStatus(status: number) {
    if (this.dataStore.studentInfo.studentStatus === status) {
      return;
    }
    const data = {
      id: this.dataStore.studentInfo.id,
      orgUserId: this.orgId,
      studentId: this.studentId,
      status: status
    };
    this.tools.showLoading();
    this.saleService.updateStudentStatus(data)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        this.tools.hideLoading();
        if (res.result === '0') {
          this.dataStore.studentInfo.studentStatus = status;
          this.tools.showToast('更新成功');
        } else {
          this.tools.showToast(res.msg);
        }
      });
  }

  ngOnInit() {
    this.getSalesCustomInfo();
    this.getFollowInfo();
    this.getClassInfo();
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}
